package com.qdlc.p2p.dal.dao.impl;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.UserVipLevelDao;
import com.qdlc.p2p.dal.dto.UserVipLevel;

@Repository("userVipLevelDao")
public class UserVipLevelDaoImpl extends BaseDaoImpl<UserVipLevel> implements UserVipLevelDao {

	@Override
	public UserVipLevel getVipLevelByLevel(int level) {
		QueryParam param = QueryParam.getInstance().addParam("level", level).addParam("isDelete", false);
		return findByCriteriaForUnique(param);
	}

	@Override
	public int getMaxLevel() {
		String sql = "select max(level) from " + Global.DB_PREFIX + "user_vip_level where is_delete=0";
        Query query = em.createNativeQuery(sql);
        int level = 0;
        if (query.getSingleResult() != null) {
        	level = (Integer) query.getSingleResult();
        }
		return level;
	}

	@Override
	public void updateLevelByLevel(int level) {
		String sql = "update " + Global.DB_PREFIX + "user_vip_level set level=level-1 where level>?";
        Query query = em.createNativeQuery(sql).setParameter(1, level);
        query.executeUpdate();
	}

	@Override
	public void update(double money, long redEnvelopeId) {
		String sql = "update " + Global.DB_PREFIX + "user_vip_level set gift_money = ? where red_envelope_rule_id = ?";
		Query query = em.createNativeQuery(sql).setParameter(1, money).setParameter(2, redEnvelopeId);
        query.executeUpdate();
	}

	@Override
	public int getCountByRedEnvelopeId(long redEnvelopeId) {
		String sql = "select count(1) from " + Global.DB_PREFIX + "user_vip_level where red_envelope_rule_id = ?";
        Query query = em.createNativeQuery(sql).setParameter(1, redEnvelopeId);
        int level = 0;
        Object obj = query.getSingleResult();
        if (obj != null) {
        	level = Integer.parseInt(obj.toString());
        }
		return level;
	}
}
